<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" v-if="isShow">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number">
              <a-input v-model="model.number" placeholder="请输入编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24">
                      <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
                        <j-dict-select-tag type="list" v-model="model.type" dictCode="sales_opportuninty_type" placeholder="请选择类型" />
                      </a-form-model-item>
                    </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="机会名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入机会名称" @blur="formatName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <!--              <j-search-select-tag v-model="model.customerId" dict="biz_customer,name,id"  />-->
              <JSelectMultiUser v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactsIds">
              <!--              <j-multi-select-tag type="list_multi" v-model="model.contactsIds" dictCode="biz_contacts,name,id" placeholder="请选择联系人IDS" />-->
              <lianxiren v-model="model.contactsIds" :query-config="lianxirenConfig" :multiple="false"
                         :url="lianxirenUrl" v-if="model.customerId"></lianxiren>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="销售阶段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesPhase">
              <j-dict-select-tag type="list" v-model="model.salesPhase" dictCode="sale_opportunity_phase"
                                 @change="salesPhaseChange" placeholder="请选择销售阶段" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">
              <j-select-user-by-dep v-model="model.directorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds">
              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="产品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productList">
              <a-button class="editable-add-btn" @click="chanPinAdd">
                添加产品
              </a-button>
              <a-table bordered
                       :dataSource="dataSource"
                       :columns="columns"
                       :pagination="false"
                       :scroll="{x:true}"
                       rowKey="id">

                <template slot="name" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="number" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                规格-->
                <template slot="specifications" slot-scope="text, record,index">
                  <span>{{ text }}</span>
                </template>
                <!--                条码-->
                <template slot="barCode" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                报价单位-->
                <template slot="unit" slot-scope="text, record">
                  <j-dict-select-tag type="list" v-model="text" dictCode="product_unit" disabled />
                </template>
                <!--                数量-->
                <template slot="num" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                单价-->
                <template slot="unitPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                折扣-->
                <template slot="discount" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                售价-->
                <template slot="quotedPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                报价小计-->
                <template slot="quotedPriceTotal" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                备注-->
                <template slot="remarks" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="operation" slot-scope="text, record,index">
                  <a @click="contactsEdit(record)">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="contactsDel(index)">删除</a>

                </template>
              </a-table>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="预计金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedAmount">
              <a-input-number v-model="model.estimatedAmount" placeholder="请输入预计金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="预计结束日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedEndTime">
              <j-date placeholder="请选择预计结束日期" v-model="model.estimatedEndTime"
                      date-format="YYYY-MM-DD" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="重要程度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="importance">
              <a-rate v-model="importance" @change="importanceChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="竞争对手" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="opponent">
              <a-input v-model="model.opponent" placeholder="请输入竞争对手"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="赢率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="winRate">
              <a-input v-model="model.winRate" disabled></a-input>
            </a-form-model-item>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
    <productInfoModal ref="productInfo" @ok="productEditOK"></productInfoModal>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUserCustom'
import JSelectUserByDepModalCustom from '@/components/jeecgbiz/modal/JSelectUserByDepModalCustom'
import lianxiren from '@/components/jeecgbiz/lianxirenCustom'
import EditableCell from '@/components/EditableCell/cell'
import productInfoModal from '@comp/ProductInfo/ProductInfoModal'

export default {
  name: 'SalesOpportunintyForm',
  components: {
    JSelectUserByDep,
    JSelectMultiUser,
    JSelectUserByDepModalCustom,
    lianxiren,
    EditableCell,
    productInfoModal
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      tableShow: true,
      //产品使用
      count: 1,
      dataSource: [],
      importance: 0,
      //联系人
      lianxirenUrl: '/sys/common/queryCustomerId?customerId=',
      lianxirenConfig: [
        { key: 'name', label: '姓名' }
        /* {key: 'leixing', label: '类型'},
        {key: 'tel', label: '电话'} */

      ],
      isShow: false,
      kehuurl: '/customer/customer/lists?filed=2',
      // 选择用户查询条件配置
      selectUserQueryConfig: [
        { key: 'phone', label: '电话' }
      ],
      columns: [
        {
          title: '产品名称',
          dataIndex: 'name',
          key: 'name',
          width: 200,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '产品编号',
          dataIndex: 'number',
          width: 200,
          key: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '规格',
          dataIndex: 'specifications',
          width: 150,
          key: 'specifications',
          scopedSlots: { customRender: 'specifications' }
        },
        {
          title: '产品条码',
          dataIndex: 'barCode',
          width: 150,
          key: 'barCode',
          scopedSlots: { customRender: 'barCode' }
        },
        {
          title: '报价单位',
          dataIndex: 'unit',
          key: 'unit',
          width: 150,
          scopedSlots: { customRender: 'unit' }
        },
        /* {
          title: '分类',
          dataIndex: 'type',
          key: 'type',
          width: 150,
          scopedSlots: { customRender: 'type' }
        }, */
        {
          title: '数量',
          dataIndex: 'num',
          key: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          key: 'unitPrice',
          width: 150,
          scopedSlots: { customRender: 'unitPrice' }
        },
        {
          title: '折扣(%)',
          dataIndex: 'discount',
          key: 'discount',
          width: 150,
          scopedSlots: { customRender: 'discount' }
        },
        {
          title: '报价',
          dataIndex: 'quotedPrice',
          key: 'quotedPrice',
          width: 150,
          scopedSlots: { customRender: 'quotedPrice' }
        },
        {
          title: '报价小计',
          dataIndex: 'quotedPriceTotal',
          key: 'quotedPriceTotal',
          width: 150,
          scopedSlots: { customRender: 'quotedPriceTotal' }
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          key: 'remarks',
          width: 150,
          scopedSlots: { customRender: 'remarks' }
        },

        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 150,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      model: {
        type: 1,
        estimatedAmount: 0,
        quotationAmount: 0
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        directorIds: [
          { required: true, message: '请选择负责人!' }
        ],
        number: [
          { required: true, message: '请输入编号!' }
        ],
        name: [
          { required: true, message: '请输入机会名称!' }
          /* {
            validator: (rule, value, callback) =>{
              let valueTrim = value.trim()
              console.log('valueTrim', valueTrim)
              if (!!!valueTrim) {
                callback(new Error('不能为空!'))
              }
            }
          } */
        ],
        customerId: [
          { required: true, message: '请输入客户!' }
        ],
        salesPhase: [
          { required: true, message: '请输入销售阶段!' }
        ],
        estimatedAmount: [
          { required: false },
          { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ]
      },
      url: {
        add: '/sales/salesOpportuninty/add',
        edit: '/sales/salesOpportuninty/edit',
        queryById: '/sales/salesOpportuninty/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }

  },
  watch: {
    'model.customerId': {
      deep: true,
      handler(newValue, oldValue) {
        this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + newValue
        if (!newValue) {
          this.model.contactsIds = ''
        }
      }
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))

  },
  methods: {
    formatName() {
      let name = this.model.name
      this.model.name = name.trim()
    },
    //产品编辑
    contactsEdit(record) {
      this.$refs.productInfo.edit(record)
    },
    productEditOK(res) {
      console.log('添加产品返回数据', res)
      const { count, dataSource } = this
      if (res.key) {
        //编辑的情况
        const dataSource = [...this.dataSource]
        let target = dataSource.find((item) => item.key == res.key)
        target = Object.assign(target, res)
        this.dataSource = dataSource
      } else {
        //新增的情况
        let newData = Object.assign(res, { key: count })
        this.dataSource = [...this.dataSource, newData]
        this.count += 1
      }
      this.totalProductsComputer()

    },
    //报价金额变化
    quotationAmountComputer(item, Nval) {
      if (this.dataSource.length <= 0) {
        console.log('无产品')
        this.model.quotationAmount = 0
        return false
      }
      console.log('总价金额变化quotationAmountComputer()')
      this.model.quotationAmount = Number(this.model.totalProducts) * Number(this.model.discountRate) / 100 + (this.model.otherExpenses ? Number(this.model.otherExpenses) : 0) - (this.model.preferentialAmount ? Number(this.model.preferentialAmount) : 0)

    },
    //移除产品列表里的某一条产品
    contactsDel(index) {
      console.log(index)
      this.dataSource.splice(index, 1)
      //重新计算总价
      this.totalProductsComputer()
      this.quotationAmountComputer('删除以重新计算总价', null)
    },
    importanceChange(e) {
      this.model.importance = e
    },

    add() {
      this.edit(this.modelDefault)
      this.isShow = false
      this.model.estimatedAmount = 0  //默认产品合计
    },
    edit(record) {
      this.isShow = true
      this.model = Object.assign({}, record)
      if (this.model.importance) {
        this.importance = Number(this.model.importance)
      }
      let count = 0
      console.log('==============record', record)
      if (record.productList) {
        record.productList.map(res => {
          res.key = count += 1
          return res
        })
        console.log('编辑初始化产品列表', record.productList)
        this.dataSource = record.productList
      }
      this.visible = true
    },
    submitForm() {
      const that = this
      this.model.productList = this.dataSource
      let obj = Object.assign({}, this.model)
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          this.model.productList = this.dataSource
          httpAction(httpurl, obj, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },

    //总价计算
    totalProductsComputer() {
      const ageSum = this.dataSource.reduce((ageSum, e) => {
        return ageSum += Number(e.quotedPriceTotal)
      }, 0)
      this.model.estimatedAmount = ageSum
      this.quotationAmountComputer()
      // return all
    },

    // input Change事件
    onInputChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key === key)
      if (target) {
        target[dataIndex] = value == '' ? '' : value
        this.dataSource = dataSource
        console.log('onInputChange', this.dataSource)
      }
    },
    //添加产品
    chanPinAdd() {
      this.$refs.productInfo.add()
    },
    jpopCallBack(e) {
      console.log('e', e)
    },
    //销售阶段状态====影响赢率
    salesPhaseChange(num) {
      console.log('num', num)
      switch (num) {
        case '1':
          this.model.winRate = 0//发现需求
          break
        case '2':
          this.model.winRate = 20//确认需求
          break
        case '3':
          this.model.winRate = 40//解决方案
          break
        case '4':
          this.model.winRate = 60//商务谈判
          break
        case '5':
          this.model.winRate = 80//招投标
          break
        case '6':
          this.model.winRate = 100//赢单
          break
        case '7':
          this.model.winRate = 0//输单
          break
        default:
          this.model.winRate = 0//取消
          break
      }
    },
    truefalseChange() {
      this.tableShow = false
      this.$nextTick(() => {
        this.tableShow = true
      })
    }
  }

}
</script>
<style scoped lang="less">

</style>